package org.example.thread4;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 守护线程演示。使用守护线程每隔 1 秒往日志文件中写入一行日志。
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2022/12/27 16:02
 */
public class MyThread8 extends Thread {

    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        try {
            //desktopDirectory：用户桌面路径
            File desktopDirectory = FileSystemView.getFileSystemView().getHomeDirectory();
            String fileName = LocalDate.now().toString() + ".log";
            File logFile = new File(desktopDirectory, fileName);
            FileWriter fileWriter = new FileWriter(logFile);
            while (true) {
                fileWriter.write(LocalDateTime.now() + " [" + threadName + "] 运行正常.\n");
                Thread.sleep(1000);
                fileWriter.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //应用程序最后一个用户线程结束后，守护线程自动立即结束，并不会保证一定会走 finally 块.
            System.out.println("[" + threadName + "] 运行结束.");
        }
    }

    public static void main(String[] args) {
        try {
            String threadName = Thread.currentThread().getName();
            MyThread8 myThread8 = new MyThread8();
            myThread8.setDaemon(true);
            System.out.println("[" + threadName + "] 启动子线程 " + myThread8.getName());
            myThread8.start();
            int total = 10;
            for (int i = 0; i < total; i++) {
                System.out.println("[" + threadName + "] " + (total - i) + " 秒后程序退出. ");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // [main] 启动子线程 Thread-0
        // [main] 10 秒后程序退出.
        // [main] 9 秒后程序退出.
        // [main] 8 秒后程序退出.
        // [main] 7 秒后程序退出.
        // [main] 6 秒后程序退出.
        // [main] 5 秒后程序退出.
        // [main] 4 秒后程序退出.
        // [main] 3 秒后程序退出.
        // [main] 2 秒后程序退出.
        // [main] 1 秒后程序退出.
    }
}
